package com.sskj.gcc.ui.fragment;


import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.bumptech.glide.Glide;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.BusData;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.LanguageUtil;
import com.sskj.gcc.R;
import com.sskj.gcc.presenter.KCoinListFragmentPresenter;
import com.sskj.gocoin.R2;
import com.sskj.level.bean.CoinType;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.ColorEnum;
import com.sskj.lib.util.CoinUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
@Route(path = RConfig.K_APP_FRAGMENT_COIN_LIST)
public class KCoinListFragment extends BaseFragment<KCoinListFragmentPresenter> {

    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.tv2)
    TextView tv2;
    private SlimAdapter<CoinBean> slimAdapter;
    private Map<String, Disposable> timeMap = new HashMap<>();
    @Autowired
    boolean isKLevel = true;

    @Override
    protected int getLayoutId() {
        return R.layout.kcoin_list_fragment;
    }

    @Override
    protected KCoinListFragmentPresenter getPresenter() {
        return new KCoinListFragmentPresenter();
    }

    @Override
    public void initView() {
        if (LanguageUtil.isChinese()) {
            tv2.setPadding(70, 0, 0, 0);
        }
        RxBus.getDefault().register(this);
        ARouter.getInstance().inject(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 2))
                .setFirstDraw(true)
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, com.sskj.gcc.R.color.commonTextEEE))
        );
        slimAdapter = SlimAdapter.create().register(R.layout.app_recy_item_coin_k_side, new SlimInjector<CoinBean>() {
            @Override
            public void onInject(CoinBean data, IViewInjector injector, List payloads) {
                if (!TextUtils.isEmpty(data.getIcon())) {
                    Glide.with(getActivity()).load(data.getIcon()).into((ImageView) injector.findViewById(R.id.viewCoin));
                }
                injector.text(R.id.tvUSDT, CoinUtil.keepCoinPrice(data.getCode(), data.getPrice()))
                        .text(R.id.tvCode, data.getName().replace("_", "/").contains("/") ? data.getName().substring(0, data.getName().replace("_", "/").indexOf("/")) : data.getName())
                        .text(R.id.tvRate, data.isUp() ? "+" + data.getChangeRate() : data.getChangeRate())
                        .background(R.id.tvRate, ContextCompat.getDrawable(App.INSTANCE, data.isUp() ? R.drawable.app_shape_corner45_03c : R.drawable.app_shape_corner45_ff5))
                        .textColor(R.id.tvUSDT, ContextCompat.getColor(App.INSTANCE, data.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()))
                        .text(R.id.tvCNY, "≈" + data.getCnyPrice() + " CNY");
            }
        });
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());

        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    if (isKLevel) {
                        BusData<CoinBean> busData = new BusData("KLevel", slimAdapter.getDataItem(position));
                        RxBus.getDefault().post(busData);
                        getActivity().finish();
                    } else {
                        RxBus.getDefault().post(new CoinType(((CoinBean) slimAdapter.getDataItem(position)).getCode()));
                        getActivity().finish();
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(List<CoinBean> data) {
        if (slimAdapter == null)
            return;
        slimAdapter.updateData(data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCoin(CoinBean stockSocketBean) {
        if (slimAdapter == null || slimAdapter.getData() == null || slimAdapter.getData().size() == 0)
            return;

        if (slimAdapter != null) {
            Flowable.fromIterable(slimAdapter.getData())
                    .filter(item -> item.getCode().equals(stockSocketBean.getCode()))
                    .subscribe(item -> {
                        stockSocketBean.setLight(true);
                        int position = slimAdapter.getData().indexOf(item);
                        slimAdapter.getData().set(position, stockSocketBean);
                        slimAdapter.notifyItemChanged(position, 1);
                        DisposUtil.close(timeMap.get(item.getCode()));
                        Disposable subscribe = Flowable.timer(1000, TimeUnit.MILLISECONDS)
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(i -> {
                                    stockSocketBean.setLight(false);
                                    slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(stockSocketBean), 1);
                                });
                        timeMap.put(item.getCode(), subscribe);
                    }, e -> {
                    });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, code = RxBusCode.REFRESH_HANGQING)
    public void refresh() {
        if (mPresenter != null) {
            mPresenter.getProduct(null);
        }
    }

    @Override
    public void initData() {
        mPresenter.getProduct(null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }
}
